package com.hxm.handlerthread;

import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView textView;
    private HandlerThread handlerThread;
    private Handler checkHandler;
    private Handler mHandler = new Handler();

    private boolean isUpdate = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.text);
        initHandlerThread();
    }

    @Override
    protected void onResume() {
        super.onResume();
        isUpdate = true;
        checkHandler.sendEmptyMessage(100);
    }

    @Override
    protected void onPause() {
        super.onPause();
        isUpdate = false;
        checkHandler.removeMessages(100);
    }

    private void initHandlerThread() {
        handlerThread = new HandlerThread("hxm");
        handlerThread.start();
        checkHandler = new Handler(handlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                updateInfo();
                if (isUpdate) {
                    checkHandler.sendEmptyMessageDelayed(100, 2000);
                }
            }
        };
    }

    private void updateInfo() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                String result = "实时更新中，当前大盘指数：<font color='btn_red'>%d</font>";
                result = String.format(result, (int) (Math.random() * 3000 + 1000));
                textView.setText(Html.fromHtml(result));
            }
        }, 2000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handlerThread.quit();
    }
}
